//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.group;

import java.math.BigDecimal;
import java.util.*;
import org.jpgolay.me.customer.Customer;
import org.jpgolay.me.order.OrderRow;
import org.jpgolay.me.payment.Payment;
import org.jpgolay.me.persistence.ObjectCRUD;
import org.jpgolay.me.sale.SalesBillPiece;
import org.jpgolay.me.sale.SalesPiece;
import org.jpgolay.me.util.MEDate;

public class GroupAction {

    public GroupAction() {
        resultat = false;
        continu = true;
        salesBillId = "";
        list = null;
        date = "";
        userId = "";
        totalGrossPrice = new BigDecimal("0.00");
        totalTax = new BigDecimal("0.00");
        totalNetPrice = new BigDecimal("0.00");
        totalTax1 = new BigDecimal("0.00");
        totalTax2 = new BigDecimal("0.00");
        totalTax3 = new BigDecimal("0.00");
        totalTax4 = new BigDecimal("0.00");
        totalTax5 = new BigDecimal("0.00");
        totalShipping = new BigDecimal("0.00");
        totalPartPayment = new BigDecimal("0.00");
        crud = new ObjectCRUD();
    }

    public boolean execute(String list[], String date) {
        this.date = date;
        this.list = list;
        group();
        return resultat;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getSalesBillId() {
        return salesBillId;
    }

    public String getCustomerId() {
        return customerId;
    }

    public BigDecimal getTotalNetPrice() {
        return totalNetPrice;
    }

    private void group() {
        for (int i = 0; i < list.length; i++) {
            if (list[i] != null) {
                if (i == 0) {
                    salesPiece = (SalesPiece) crud.read(list[i], 22);
                    if (salesPiece != null) {
                        firstBl();
                    } else {
                        continu = false;
                    }
                } else if (continu) {
                    salesPiece = (SalesPiece) crud.read(list[i], 22);
                    if (salesPiece != null) {
                        if (salesPiece.getCustomerId().equals(customerId)) {
                            nextBl();
                        } else {
                            continu = false;
                        }
                    } else {
                        continu = false;
                    }
                }
            }
        }

        if (continu) {
            createFact();
            updatePayment();
            resultat = true;
        } else {
            resultat = false;
        }
    }

    private void firstBl() {
        customerId = salesPiece.getCustomerId();
        compagnyId = salesPiece.getCompagnyId();
        salesPersonId = salesPiece.getSalesPersonId();
        nextBl();
    }

    private void nextBl() {
        totalShipping = totalShipping.add(salesPiece.getShippingPrice());
        totalGrossPrice = totalGrossPrice.add(salesPiece.getGrossPrice());
        totalTax = totalTax.add(salesPiece.getTotalTax());
        totalNetPrice = totalNetPrice.add(salesPiece.getNetPrice());
        totalTax1 = totalTax1.add(salesPiece.getTax1());
        totalTax2 = totalTax2.add(salesPiece.getTax2());
        totalTax3 = totalTax3.add(salesPiece.getTax3());
        totalTax4 = totalTax4.add(salesPiece.getTax4());
        totalTax5 = totalTax5.add(salesPiece.getTax5());
        totalPartPayment = totalPartPayment.add(salesPiece.getPartPayment());
    }

    private void createFact() {
        salesBillId = (String) crud.create(25, "F");
        salesBillPiece = (SalesBillPiece) crud.read(salesBillId, 25);
        if (salesBillPiece != null) {
            salesBillPiece.setDate(date);
            salesBillPiece.setCompagnyId(compagnyId);
            salesBillPiece.setSalesPersonId(salesPersonId);
            salesBillPiece.setCustomerId(customerId);
            salesBillPiece.setUpdateUserId(userId);
            salesBillPiece.setNetPrice(totalNetPrice);
            salesBillPiece.setGrossPrice(totalGrossPrice);
            salesBillPiece.setTotalTax(totalTax);
            salesBillPiece.setTax1(totalTax1);
            salesBillPiece.setTax2(totalTax2);
            salesBillPiece.setTax3(totalTax3);
            salesBillPiece.setTax4(totalTax4);
            salesBillPiece.setTax5(totalTax5);
            salesBillPiece.setShippingPrice(totalShipping);
            salesBillPiece.setPartPayment(totalPartPayment);
            salesBillPiece.setSubTotal(new BigDecimal("0.00"));
            salesBillPiece.setLocking(new Integer(0));
            salesBillPiece.setShippingTax(new BigDecimal("0.00"));
            salesBillPiece.setDueDate(getDueDate());
            if (crud.update(salesBillPiece, 25)) {
                updateRowsAndDeliveryOrder();
            }
        }
    }

    private String getDueDate() {
        Customer customer = (Customer) crud.read(customerId, 27);
        if (customer != null) {
            return (new MEDate()).getDateAddXDay(date, customer.getEcheancePaiement().intValue());
        } else {
            return null;
        }
    }

    private void updateRowsAndDeliveryOrder() {
        SalesPiece sp = null;
        ArrayList l = null;
        OrderRow orderRow = null;
        OrderRow orderRowTxt = null;
        Integer pk = null;
        int line = 0;
        for (int i = 0; i < list.length; i++) {
            sp = (SalesPiece) crud.read(list[i], 22);
            if (sp != null) {
                sp.setBillReference(salesBillId);
                salesPiece.setPrepare(new Integer(1));
                crud.update(sp, 22);
            }
            java.util.Collection c = crud.readAll(list[i], 28);
            if (c != null) {
                pk = (Integer) crud.create(28, null);
                if (pk != null) {
                    orderRowTxt = (OrderRow) crud.read(pk, 28);
                    orderRowTxt.setLine(new Integer(line));
                    orderRowTxt.setDesignation("BL " + sp.getId() + " du " + sp.getDate() + " (" + sp.getGrossPrice().setScale(2) + "HT)");
                    orderRowTxt.setFactureId(salesBillId);
                    orderRowTxt.setStatus(new BigDecimal(0));
                    crud.update(orderRowTxt, 28);
                    line++;
                }
                l = new ArrayList(c);
                for (Iterator it = l.iterator(); it.hasNext();) {
                    orderRow = (OrderRow) it.next();
                    orderRow.setFactureId(salesBillId);
                    orderRow.setLine(new Integer(line));
                    orderRow.setLine(new Integer(1 + orderRow.getLine().intValue()));
                    crud.update(orderRow, 28);
                    line++;
                }

            }
        }

    }

    private void updatePayment() {
        for (int i = 0; i < list.length; i++) {
            java.util.Collection listPayment = crud.readAll(list[i], "BL-CL", 26);
            if (listPayment != null) {
                HashSet ref = new HashSet(listPayment);
                Iterator it = ref.iterator();
                Payment payment = null;
                for (; it.hasNext(); crud.update(payment, 26)) {
                    payment = (Payment) it.next();
                    payment.setPieceId(salesBillId);
                    payment.setPrefix("F-CL");
                }

            }
        }

    }
    private boolean resultat;
    private boolean continu;
    private Integer compagnyId;
    private Integer salesPersonId;
    private String customerId;
    private String salesBillId;
    private String list[];
    private String date;
    private String userId;
    private BigDecimal totalGrossPrice;
    private BigDecimal totalTax;
    private BigDecimal totalNetPrice;
    private BigDecimal totalTax1;
    private BigDecimal totalTax2;
    private BigDecimal totalTax3;
    private BigDecimal totalTax4;
    private BigDecimal totalTax5;
    private BigDecimal totalShipping;
    private BigDecimal totalPartPayment;
    private ObjectCRUD crud;
    private SalesPiece salesPiece;
    private SalesBillPiece salesBillPiece;
}
